/***
 * post 请求
 * @param url 地址
 * @param options  参数 json
 * @returns json
 */
/****
 * 用户登出
 * @return true or false
 */
import fetch from "dva/fetch";
import {
	PAGE_MENU_REQUEST, USER_PERMISSION, PAGE_LIST_CONFIG_REQUEST, PAGE_LIST_DY_CONFIG_REQUEST, LOGIN, UPDATE_PWD, CHECK_TOKEN, CHECKUSER,
	SENDVCODE, FPWDDONE,
	GET_DASHBOARD_CONFIG, GET_WIDGET_CONFIG
} from "../config/Config";
import moment from "moment";
import mockjs from 'mockjs';
import { Modal } from 'antd-mobile';
import md5 from "md5"
export function myFetch(obj, method = "POST") {
	let { apiInfo } = obj;
	if (apiInfo && apiInfo.use_mock_data == 1) {
		let data = mockjs.mock(apiInfo.mock).data;
		console.log("mockdata", data);
		return new Promise(function (resolve, reject) {
			resolve({ code: 10200, data });
		});
	}
	let { url, params } = filterApi(obj);
	return fetch(url, setData(method, params)).then(checkStatus).then(parseJSON).then((data) => correctData(data)).catch((err) => {
		return {
			data: { ...err }
		}
	})
}


export function setLogout(obj) {

	obj = obj || {};
	obj = {
		...obj,
		img_user: "",
		mi_token: "",
		copyright: "",
		copyright_url: "",
		api_url: "",
		logo: "",
		website: "",
		config: "",
		webname: "",
		user_id: "",
		username: "",
		role_id: "",
		historyTop: "",
		mi_uuid: "",
		menus: "",
		permissions: "",
		prevPath: ""
	};
	for (let i in obj) {
		localStorage.setItem(MI_APP_CODE + i, "");
		localStorage[MI_APP_CODE + i] = ""
		localStorage.removeItem(MI_APP_CODE + i);
	}
	console.log("location", location, getParmaFromUrl(location.href));
	let urlParams = getParmaFromUrl(location.href);
	let { hzl_username } = urlParams;
	if (!isNull(hzl_username)) {//从汇治理跳转过来,url上带了汇治理的用户的信息,这个时候跳转到自动登录时,需要用url上传过来的用户信息进行登录.
		localStorage.setItem(MI_APP_CODE + "hzl_username", hzl_username);
	}
	// setTimeout(() => {
	if (browser.isInApp) {
		Func.callHander(bridge, "logoutSuccess", { ...obj });//解决安卓 浏览器的localStorage清不掉的bug
	}
	else {

		window.location.reload()
	}
	// })
}



/***
 * 处理请求参数
 * @param param
 * @returns {string}
 */
function handleParams(param) {
	return "token=" + localStorage[MI_APP_CODE + "mi_token"] + "&data=" + JSON.stringify(param);
}
export function getHost() {
	return location.origin;
}
export function handleUrl(url) {
	if (isNull(url)) {
		return url
	}
	else {
		let base_url = getHost();
		url = url.replace(/\{\{base_url\}\}/g, base_url);
		url = url.replace(/\{\{_api_url\}\}/g, API_URL);
		if ((url.substr(0, 4) == "http" || url.substr(0, 5) == "https")) {
			return url;
		}
		return API_URL + url;
	}
}
export function handleFile(url) {
	if (url && (url.substr(0, 4) == "http" || url.substr(0, 5) == "https")) {
		return url;
	}
	let prefix = "";
	try {
		let config = localStorage.getItem(MI_APP_CODE + "config");
		prefix = JSON.parse(config).file_root;
	} catch (e) {

	}
	if (isNull(prefix)) {
		prefix = ""
	}
	return prefix + url;
}

function parseJSON(response) {
	return response.json();
}
function checkStatus(response) {
	if (response.status >= 200 && response.status < 300) {
		return response;
	}
	const error = new Error(response.statusText);
	error.code = response.status;
	error.msg = response.statusText;
	error.url = response.url;
	throw error;
}
function correctData(data) {
	data.data = data.data || data.dataList || [];
	return data;
}
function setData(method, params) {
	return {
		"method": method,
		headers: {
			// 'Content-Type':'application/x-www-form-urlencoded;charset=utf-8',
			// "Accept":"application/json"
		},
		body: params
	}
}
export function upload({ url, params }) {
	return fetch(url, {
		"method": "POST",
		// "headers":{
		// 	"token":localStorage[MI_APP_CODE+"mi_token"]
		// },
		body: params
	}).then(checkStatus).then(parseJSON).then((data) => correctData(data)).catch((err) => ({ data: { ...err } }));
}
export function request(param) {
	let req = filterApi(param);
	const { url, params } = req;
	return fetch(url, setData("POST", params)).then(checkStatus).then(parseJSON).then((data) => correctData(data)).catch((err) => ({ data: { ...err } }));
}
//指定url参数 调用方法
export function requestUrl(url, params) {
	return fetch(url, setData("POST", handleParams(params))).then(checkStatus).then(parseJSON).then((data) => correctData(data)).catch((err) => ({ data: { ...err } }));
}

export function login(param) {
	let obj = {
		apiInfo: {
			url: LOGIN
		},
		apiParams: param,
		isEditCreate: true
	};
	return myFetch(obj);
}
export function register(param) {
	let obj = {
		apiInfo: {
			url: "member/register"
		},
		apiParams: param,
		isEditCreate: true
	};
	return myFetch(obj);
}
export function login_h5({ data, apiParams }) {
	let obj = {
		apiInfo: {
			url: "login_h5"
		},
		apiParams,
		data,
		isEditCreate: true
	};
	return myFetch(obj);
}
export function loginhzl( param ) {
	let obj = {
		apiInfo: {
			url: "/xuhui/loginhzl"
		},
		apiParams:param,
		isEditCreate: true
	};
	return myFetch(obj);
}
export function changePwd(param) {
	let obj = {
		apiInfo: {
			url: UPDATE_PWD
		},
		data: param,
		isEditCreate: true
	};
	return myFetch(obj)
}
//生成4位随机数
export function MI_S4() {
	return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
}
//生成UUID
export function getUUID() {
	var uuid = localStorage[MI_APP_CODE + "mi_uuid"];
	if (!uuid) {
		uuid = (MI_S4() + "-" + MI_S4() + "-" + MI_S4() + "-" + new Date().valueOf());
	}
	localStorage[MI_APP_CODE + "mi_uuid"] = uuid;
	return uuid;
}
export function getToken() {
	let { width, height } = window.screen;
	let obj = {
		apiInfo: {
			url: GET_TOKEN
		},
		apiParams: {
			app_code: MI_APP_CODE,
			version: MI_VERSION,
			uuid: getUUID(),
			screen: width + "*" + height
		},
		isEditCreate: true
	};
	return myFetch(obj)
}
export function checkToken(token) {
	token = token || localStorage[MI_APP_CODE + "mi_token"];
	if (isNull(token)) {
		return {
			code: 10400
		};
	}
	else {
		let obj = { apiInfo: { url: CHECK_TOKEN }, isEditCreate: true };
		return myFetch(obj);
	}
}
//获取token
export function getMenu() {
	return fetch(PAGE_MENU_REQUEST, setData("POST", "token=" + localStorage[MI_APP_CODE + "mi_token"])).then(checkStatus).then(parseJSON).then((data) => correctData(data)).catch((err) => ({ data: { ...err } }));
}
//获取权限
export function getPermission() {
	return fetch(USER_PERMISSION, setData("POST", "token=" + localStorage[MI_APP_CODE + "mi_token"])).then(checkStatus).then(parseJSON).then((data) => correctData(data)).catch((err) => ({ data: { ...err } }));
}
//获取LIST 配置
export function getListConfig(search) {
	return fetch(PAGE_LIST_CONFIG_REQUEST, setData("POST", handleParams(search))).then(checkStatus).then(parseJSON).then((data) => correctData(data)).catch((err) => ({ data: { ...err } }));
}

//获取DASHBOARD 配置
export function getDashBoardConfig(search) {
	return fetch(GET_DASHBOARD_CONFIG, setData("POST", handleParams(search))).then(checkStatus).then(parseJSON).then((data) => correctData(data)).catch((err) => ({ data: { ...err } }));
}

//获取Widget 配置
export function getWidgetConfig(search) {
	return fetch(GET_WIDGET_CONFIG, setData("POST", handleParams(search))).then(checkStatus).then(parseJSON).then((data) => correctData(data)).catch((err) => ({ data: { ...err } }));
}



//获取LIST_DY 配置
export function getListDyConfig(search) {
	return fetch(PAGE_LIST_DY_CONFIG_REQUEST, setData("POST", handleParams(search))).then(checkStatus).then(parseJSON).then((data) => correctData(data)).catch((err) => ({ data: { ...err } }));
}

//获取视图组件 配置
export function getViewConfig(url, search) {
	return fetch(url, setData("POST", handleParams(search))).then(checkStatus).then(parseJSON).then((data) => correctData(data)).catch((err) => ({ data: { ...err } }));
}

export function getParmaFromUrl(url) {
	if (!url) {
		url = window.location.href;
	}
	url = decodeURIComponent(url);
	if (url.indexOf("?") == -1) {
		return {}
	}
	let search = url.substring(url.indexOf("?") + 1, url.length);
	let serachArr = search.split("&");
	let obj = {};
	serachArr.map(function (item) {
		let itemArr = item.split("=");
		obj[itemArr[0]] = itemArr[1]
	});
	return obj
}
export function isNull(val) {
	return val === undefined || val === null || val === ""
}
export function filterApi(arg) {
	// console.log("arg",arg);
	let { apiInfo, data, pager, apiParams, isEditCreate } = arg;
	let api = handleUrl(apiInfo.url);
	apiParams = {
		...apiParams, ...getParmaFromUrl(api)
	};
	let iparams = apiInfo.params;
	let req = {};
	if (!isNull(iparams) && iparams.length > 0) {
		for (let item of iparams) {
			let itemKey = item.key;
			if (!isNull(item.value)) {
				req[itemKey] = item.value;
			}
			else {
				if (item.data_type == "jsonobject" || item.data_type == "object") {
					let obj1 = {
						[itemKey]: {}
					};
					for (let i in data) {
						if (i.toString().substring(0, itemKey.toString().length + 2) == itemKey + "->") {
							let arr = i.split("->");
							if (arr.length == 2) {
								arr.map((item, key) => {
									if (key == 0) {
										if (!obj1[arr[0]]) {
											obj1[arr[0]] = {}
										}
									}
									if (key == 1) {
										obj1[arr[0]][arr[1]] = data[i]
									}
								})
							}
							else if (arr.length == 3) {
								arr.map((item, key) => {
									if (key == 0) {
										if (!obj1[arr[0]]) {
											obj1[arr[0]] = {}
										}
									}
									if (key == 1) {
										if (!obj1[arr[0]][arr[1]]) {
											obj1[arr[0]][arr[1]] = {}
										}
									}
									if (key == 2) {
										obj1[arr[0]][arr[1]][arr[2]] = data[i]
									}
								})
							}
						}
					}
					if (item.data_type == "jsonobject") {
						obj1 = {
							[itemKey]: JSON.stringify(obj1[itemKey])
						}
					}
					for (let k in obj1) {
						req[k] = obj1[k]
					}
				}
				else {
					if (!isNull(item.store_field)) {
						if (item.store_field == "_platform") {
							req[itemKey] = browser.platform
						}
						else {
							req[itemKey] = data[item.store_field];
						}
					}
					else {
						req[itemKey] = data[itemKey];
					}
				}
			}
			//搜索或者是部分提交时  新增修改一般不会经过这里
			if (!isNull(req[itemKey])) {
				if (item.data_type == "number") {
					req[itemKey] = Number(req[itemKey]);
				}
				else if (item.data_type == "timestamp") {
					req[itemKey] = moment(req[itemKey]).format()
				}
				else if (item.data_type == "array") {
					req[itemKey] = req[itemKey];
				}
				else {
					req[itemKey] = req[itemKey].toString();
				}
			}
		}
	}
	else {
		if (isEditCreate) {
			req = data
		}
	}
	if (!isEditCreate) {
		for (let i in req) {
			if (isNull(req[i])) {
				req[i] = undefined
			}
		}
	}
	req = {
		params: req
	};
	if (!isNull(pager) && apiInfo.page_enable == 1) {
		req = {
			...req, ...pager
		}
	}
	if (apiParams) {
		req = { ...req, ...apiParams }
	}
	for (let i in req) {
		//把 _lc,_fc,_sc,_ec这些参数换成_c
		if (i == "_lc" || i == "_fc" || i == "_sc" || i == "_ec") {
			req._c = req[i];
			delete req[i];
		}
		// 把 sorter换成sorters参数
		if (i == "sorter") {
			req.sorters = req[i];
			delete req[i]
		}
		//把pagesize pageindex换成page_size page_index
		if (i == "pagesize" || i == "pageSize") {
			req.page_size = req[i];
			delete req[i]
		}
		if (i == "pageindex" || i == "pageIndex") {
			req.page_index = req[i];
			delete req[i]
		}
	}
	let token = localStorage[MI_APP_CODE + "mi_token"];
	console.log(token)
	let _subsystem = 0;
	let locale = "zh-CN";
	console.log(req);
	// const reqOrder={};
  // Object.keys(req).sort().forEach(function(key) {
  //   reqOrder[key] = req[key];
  // });
  // console.log(reqOrder);
	let obj = {
		t: new Date().valueOf(),
		subsystem: _subsystem,
		token,
		locale,
		data: req
	};
	console.log(obj);
  console.log(JSON.stringify(obj));
  console.log(JSON.stringify(obj) + MI_SECRET);
//   const ordered={};
//   Object.keys(obj).sort().forEach(function(key) {
//     ordered[key] = obj[key];
//   });
// console.log(JSON.stringify(ordered));
  let sign = md5(JSON.stringify(obj) + MI_SECRET);
  console.log(sign)
	obj = {
		...obj,
		sign
	};
	obj = JSON.stringify(obj);
	return {
		url: api,
		params: obj
	};
}
export function checkUser(param, api_url) {
	api_url = api_url || localStorage[MI_APP_CODE + "api_url"];
	let params = "t=" + new Date().valueOf() + "&token=" + localStorage[MI_APP_CODE + "mi_token"] + "&data=" + JSON.stringify(param);
	return fetch(api_url + CHECKUSER, setData("POST", params)).then(checkStatus).then(parseJSON).then((data) => correctData(data)).catch((err) => ({ data: { ...err } }));
}
export function sendVcode(param, api_url) {
	api_url = api_url || localStorage[MI_APP_CODE + "api_url"];
	let params = "t=" + new Date().valueOf() + "&token=" + localStorage[MI_APP_CODE + "mi_token"] + "&data=" + JSON.stringify(param);
	return fetch(api_url + SENDVCODE, setData("POST", params)).then(checkStatus).then(parseJSON).then((data) => correctData(data)).catch((err) => ({ data: { ...err } }));
}
export function pwdDone(param, api_url) {
	api_url = api_url || localStorage[MI_APP_CODE + "api_url"];
	let params = "t=" + new Date().valueOf() + "&token=" + localStorage[MI_APP_CODE + "mi_token"] + "&data=" + JSON.stringify(param);
	return fetch(api_url + FPWDDONE, setData("POST", params)).then(checkStatus).then(parseJSON).then((data) => correctData(data)).catch((err) => ({ data: { ...err } }));
}

